﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor
{
    [Tools.SelectableTool]
    public class RotateTool : Tool
    {
        List<Operations.TransformItem> MultiSelectTransforms = new List<Operations.TransformItem>();
        Vector2 MouseDelta;
        bool Changes = false;

        public override System.Drawing.Image GetIcon() { return System.Drawing.Image.FromFile("ToolIcons/rotate.bmp"); }
        
        public override void MouseDown(MouseInputState InputState, EditorState EditorState)
        {
            MultiSelectTransforms.Clear();
            var ItemsSelected = EditorState.GetEverythingSelected();
            foreach (var Item in ItemsSelected)
            {
                var SelectedObject = EditorState.GetSelectionObject(Item);
                var Rotatable = SelectedObject as Data.Rotatable;
                if (Rotatable != null)
                {
                    var TransformationTag = Rotatable.PrepareToRotate();
                    
                    MultiSelectTransforms.Add(new Operations.TransformItem
                    {
                        TransformationTag = TransformationTag,
                        Transformee = Rotatable
                    });
                }
            }

            MouseDelta = Vector2.Zero;
            Changes = false;
        }

        public override void MouseUp(MouseInputState InputState, EditorState EditorState)
        {
            if (Changes && MultiSelectTransforms.Count != 0)
                EditorState.PerformOperation(new Operations.Rotate(MultiSelectTransforms, MouseDelta.Y,
                    (InputState.Modifiers & System.Windows.Forms.Keys.Alt) > 0));
            MultiSelectTransforms.Clear();
        }

        public override void MouseMove(MouseInputState InputState, EditorState EditorState)
        {
            MouseDelta += InputState.Delta;
            Changes = true;
            foreach (var Item in MultiSelectTransforms)
            {
                (Item.Transformee as Data.Rotatable).ApplyRotation(Item.TransformationTag, MouseDelta.Y);
                if ((InputState.Modifiers & System.Windows.Forms.Keys.Alt) > 0)
                    (Item.Transformee as Data.Rotatable).Snap(Operations.Snapper.GetSnapper(EditorState));
            }
        }
    }
}
